package org.fujene.diskblock.blockwise;

import java.io.ByteArrayOutputStream;
import java.io.File;

import org.fujene.diskblock.DiskBlock;
import org.fujene.memoryblock.MemoryBlock;
import org.fujene.memoryblock.blockwise.BlockwiseInvertIndexBlock;
import org.fujene.structure.Constants;
import org.fujene.structure.InvertIndexData;
import org.fujene.structure.LookupPointer;
import org.fujene.toolbox.ByteConverter;

/**
 * InvertIndexBlockのサブセットとして機能します。
 * 相対ポインタに対応しています。
 */
public class BlockwiseInvertIndexDiskBlock extends DiskBlock {
	public BlockwiseInvertIndexDiskBlock(File fileDesc) throws Exception {
		super(fileDesc);
	}
	
	public BlockwiseInvertIndexDiskBlock(int ID, File fileDesc, int defaultBodySize, int defaultOptionSize){
		super(ID, fileDesc, Constants.MEMORY_TYPE_INVINDEX, defaultBodySize, defaultOptionSize);
	}

	public BlockwiseInvertIndexDiskBlock(BlockwiseInvertIndexBlock memBlock, String dir) {
		super(memBlock, dir);
	}
	
	// 相対ポインタ対応
	public InvertIndexData getInvertIndex(int ptr) throws Exception {
		LookupPointer prevPtr, contentPtr;
		int termfreq;
		
		prevPtr = ByteConverter.getRelativePtr(getBody(ptr, RELPTR));
		if(prevPtr.equals(Constants.emptyRelativePtr))
			prevPtr = null;
		else
			prevPtr.block += this.getID();
			
		ptr += RELPTR;
		
		contentPtr = ByteConverter.getRelativePtr(getBody(ptr, RELPTR));
		if(contentPtr.equals(Constants.emptyRelativePtr))
			contentPtr = null;
		else
			contentPtr.block += this.getID();
		ptr += RELPTR;
		
		termfreq = ByteConverter.byteToInt(getBody(ptr, TERMFREQ));
		
		return new InvertIndexData(prevPtr, contentPtr, termfreq);
	}
	
	@Override
	public void readToMemory(MemoryBlock memBlock) {
		if(memBlock instanceof BlockwiseInvertIndexBlock){
			try {
				memBlock.setOption(0, this.getOption(0));
				memBlock.setBody(this.getBody(0, this.bodySize), 0);
				memBlock.setBodyVacancy(this.bodyVacancy);
			} catch (Exception e) {
			}
		}
	}

	@Override
	public byte[] getData() throws Exception {
		ByteArrayOutputStream stream = new ByteArrayOutputStream(this.bodySize + 4);
		
		stream.write(ByteConverter.intToByte(this.getOption(0), 4));
		stream.write(this.getBody(0, this.bodySize));
		
		return stream.toByteArray();
	}
}
